﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Linq;
using System.Collections.Generic;
using Twipler.App.Parse.Code;
using Twipler.App.Render.Tree;
using Twipler.App.Machine;


namespace Twipler.App.Parse.Html.Consumers
{
    [Consumer(OpenTag="delay", CloseTag="delayend", OptionalTags= new string[] {"waiting"})]
    public class DelayConsumer : TemplateConsumer
    {
        public class DelayedConsumerParameters : TemplateParameters
        {
            [HtmlArgument(TokenParser.TokenType.String, true)]
            public string QueryString;

            [HtmlArgument(TokenParser.TokenType.InstructionList, true)]
            public List<Instruction> RepeatIf;
        }
        
        public DelayConsumer()
        {
            Parameters = new DelayedConsumerParameters();
        }

        public override App.Render.Tree.AbstractItem Process(Template template, TemplateConsumer parent)
        {
            ReadArguments(template);
            if (template.HasErrors)
                return ParseErrorItem.Create(template.Errors.First().Message);

            template.SkipWhiteSpace();
            if (template.Peek(Template.EndMarker, false) == false)
                return Error(template, "Missing template close tag (" + Template.EndMarker + ")");

            template.SkipOver(Template.EndMarker);

            
            string tag = string.Empty;
            AbstractItem delayedPart = template.ParseUntil(new string[] { "waiting", "delayend" }, ref tag, this);
            if (tag != string.Empty)
                template.SkipOver(Template.EndMarker);

            AbstractItem waitingPart = null;
            if (tag.ToLower() == "waiting")
            {
                waitingPart = template.ParseUntil(new string[] { "delayend" }, ref tag, this);
                if (tag != string.Empty)
                    template.SkipOver(Template.EndMarker);
            }

			return App.Render.Tree.DelayItem.Create(delayedPart, waitingPart, ((DelayedConsumerParameters)Parameters).QueryString, ((DelayedConsumerParameters)Parameters).RepeatIf);

        }

    	
    }
}